package com.example.capsule_netty.netty;

import com.example.capsule_netty.bean.MessageBean;
import com.example.capsule_netty.configuration.ActionType;
import com.example.capsule_netty.impl.MessageActionImpl;
import com.example.capsule_netty.protocol.MessageBeanProtocol;
import com.example.capsule_netty.utils.SpringUtils;
import com.google.gson.Gson;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/27 19:43
 */
@Slf4j
public class NettyHandler extends SimpleChannelInboundHandler<MessageBeanProtocol> {

    private int count = 0;

    private Gson gson;
    private MessageActionImpl messageActionImpl;
    private static int maxCount = 3;
    public String currentUserImei;

    public NettyHandler() throws Exception {
        gson = new Gson();
        messageActionImpl = (MessageActionImpl) SpringUtils.getBeanByName("messageActionImpl");
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageBeanProtocol messageBeanProtocol) throws Exception {
        byte[] content = messageBeanProtocol.getContent();
        String msg = new String(content, StandardCharsets.UTF_8);
        MessageBean messageBean = null;
        try {
            messageBean = gson.fromJson(msg, MessageBean.class);
            //心跳数据包
            if (messageBean.getSenderId() != null && messageBean.getSenderId().equals("-10000")) {
                return;
            }
        } catch (Exception e) {
            System.out.println(e);
            log.error("不合法的传入消息参数");
        }
        // Assert.notNull(messageBean, "messageBean must not null!");
        int actionType = messageBean.getActionType();

        if (actionType == ActionType.CONNECT_TYPE) {
            messageActionImpl.dealConnectAction(ctx, messageBean);
        } else if (actionType == ActionType.REGISTER_TYPE) {
            messageActionImpl.dealRegisterAction(ctx, messageBean);
            currentUserImei = messageBean.getImei();
        } else if (actionType == ActionType.CHAT_TYPE) {
            messageActionImpl.dealChatAction(ctx.channel(), messageBean);
        } else if (actionType == ActionType.SIGN_TYPE) {
            messageActionImpl.dealSignAction(ctx, messageBean);
        } else if (actionType == ActionType.CLOSE_TYPE) {
            messageActionImpl.dealClose(ctx,currentUserImei);
        }
    }

    private static DefaultChannelGroup userGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        userGroup.add(ctx.channel());

    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        messageActionImpl.dealClose(ctx,currentUserImei);
        messageActionImpl.dealExceptionAction(currentUserImei);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            maxCount--;

            if (((IdleStateEvent) evt).state() == IdleState.ALL_IDLE) {
                if (maxCount <= 0) {
                    messageActionImpl.dealClose(ctx,currentUserImei);
                }
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        messageActionImpl.dealExceptionAction(currentUserImei);
    }


}
